package com.controller.front_controller;

import com.mypg.Test;
import com.service.TestService;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/front_test_real")
@Controller
public class FrontTestRealController {

    @Autowired
    TestService testService;

    @Autowired
    UserService userService;

    @RequestMapping("/save_test.do")
    @ResponseBody
    public void doSave_test(HttpSession session,String question_class,int grade,String finish_time){
        String user_name= (String) session.getAttribute("user_name");
        int user_id=userService.selectUserByUser_name(user_name).getUser_id();
        Test test=new Test();
        test.setUser_id(user_id);
        test.setQuestion_class(question_class);
        test.setTest_name(testService.selectTestCountByUser_idAndQuestion_class(user_id,question_class)+1);
        test.setGrade(grade);
        test.setFinish_time(finish_time);
        testService.insertTest(test);
    }

    @RequestMapping("/init_test_tongji.do")
    @ResponseBody
    public Map<String,Object> doInit_test_tongji(HttpSession session,String question_class){
        Map<String,Object> map=new HashMap<>();
        String user_name= (String) session.getAttribute("user_name");
        int user_id=userService.selectUserByUser_name(user_name).getUser_id();
        List<Test> testList=testService.selectTestByUser_idAndQuestion_class(user_id,question_class);
        int test_times=testList.size();
        int pass_times=0;
        int fail_times=0;
        double pass_percent=0.0;
        for(Test test:testList){
            if(test.getGrade()>=60)
                pass_times++;
            else
                fail_times++;
        }
        if(test_times!=0) {
            pass_percent = (double) pass_times / test_times;
            pass_percent *= 100;
            pass_percent = (double) Math.round(pass_percent * 10) / 10;
        }
        map.put("testList",testList);
        map.put("test_times",test_times);
        map.put("pass_times",pass_times);
        map.put("fail_times",fail_times);
        map.put("pass_percent",pass_percent);
        return map;
    }

}
